// pages/user/user.js
//引入全局变量 其他页面要用用户信息也可以 写在onshow
import { request } from "../../request/index.js";

const reqData = {}

const app = getApp()
Page({
  useStore: true,
  /**
   * 页面的初始数据
   */
  data: {
    // 地址的标记
    mark: true,
    address: "收货地址",
    openId: '',
    isStatus: false,
    users: {},
    userId: '',
    userPhone: '',
    // 电话的标记
    phoneMark: true,
    option1: [
    ],
    option2: [
    ],
    option3: [
    ],
    value1: 0,
    value2: 0,
    value3: 0,
    show: false,
  },

// 改变第一级
changeOption1({ detail }) {
  var that = this
  console.log(detail)
  request({
    url: '/userPage/getBuilding',
    data:{
      region: this.data.option1[detail].text
    }
  })
  .then(result=>{
    console.log(result)
    that.setData({
      option2: result.data.data.list,
      value2:0,
      value3:0
    })
    console.log( 'add2Sucess' )
    reqData.value1 = that.data.option1[detail].text;
  console.log(reqData)
  })
  .catch(err=>{
    console.log(err)
  })
  
},

// 改变第二级
changeOption2({ detail }) {
  console.log(detail)
  request({
    url: '/userPage/getRoom',
    data:{
      region: reqData.value1,
      building: this.data.option2[detail].text,
    }
  })
  .then(result=>{
    console.log(result)
    this.setData({
      option3: result.data.data.list,
      value3:0
    })
    console.log( 'add3Sucess' )
  reqData.value2 = this.data.option2[detail].text;
  console.log(reqData)
  })
  .catch(err=>{
    console.log(err)
  })
},

// 改变第三级
changePage({ detail }) {
  console.log(detail)
  reqData.value3 = this.data.option3[detail].text;
  console.log(reqData);
},

// 唤起弹窗
outPut() {
  var value_add = wx.getStorageSync('add')
    if (value_add) {
      this.setData({
        mark: true,
        address: value_add
      }),
        console.log(value_add)
    }
  this.setData({
    show: !this.data.show,
    mark: true
  })
},

// 改变状态 切换收货地址
ChangeMark() {
  this.setData({ 
    mark: false,
    show: true 
  })
  // 第一级地址
  request({
    url: '/userPage/getRegion'
  })
  .then(result=>{
    console.log(result)
    this.setData({
      option1: result.data.data.list
    })
    console.log( 'add1Sucess' )
  })
  .catch(err=>{
    console.log(err)
  })
},

// 改变收货地址
ChangeAdd() {
  console.log(reqData);
  this.setData({
    address: reqData.value1 + reqData.value2 + reqData.value3
  })
  console.log(this.data.address)
  wx.setStorageSync('add', this.data.address)
  this.setData({ 
    mark: true,
    show: false
  })
  request({
    url: '/user/updateInfo', data: {
      address: this.data.address
    }, method: 'PUT'
  })
    .then(result => {
      console.log(result);
    })
},

  // 登录获取数据
  login() {
    const that = this;
    wx.login({
      timeout: 20000,
      success(res) {
        wx.request({
          url: 'https://dogborther.top/user/login',
          data: {
            code: res.code
          },
          success(res1) {
            wx.setStorageSync('token', res1.data.data.token)
            console.log(res1, "***********");
            if(res1.data.data.user.phoneNum){
              that.setData({
                userPhone: res1.data.data.user.phoneNum,
                phoneMark : true,
              })
            wx.setStorageSync('userPhone', that.data.userPhone)
            }
            if(res1.data.data.user.address){
              that.setData({
                address: res1.data.data.user.address,
                Mark : !that.data.Mark,
              })
              wx.setStorageSync('add', that.data.address)
            }
          }, fail(err) {
            console.log(err);
          }
        })
      }
    })
    wx.getUserProfile({
      desc: '展示用户信息',
      success(res) {
        console.log(res.userInfo);
        let user = res.userInfo
        that.setData({
          users: user,
          isStatus: true
        })
        wx.setStorageSync('userinfo', user)
        app.globalData.userInfo = user
        app.store.setState({
          userMessage: user
        })

        //传数据给后台
        request({
          url: '/user/updateInfo', data: {
            uid: that.data.userId,
            userName: that.data.users.nickName,
            avatar: that.data.users.avatarUrl,
            openId: that.data.openId,
            address: that.data.address
          }, method: 'PUT'
        })
          .then(result => {
            console.log(result);
            wx.showToast({
              title: '登录成功',
            })
          })
      }
    })

  },

  // 获得手机号
  getPhoneNumber(e) {
    var that = this
    console.log(e)
    request({
      url: '/user/getPhoneInfo',
      method: "POST",
      data: {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv
      }
    })
    .then(result=>{
      console.log(result)
      let data = JSON.parse(result.data.data.info)
      console.log(data)
      let phone = data.phoneNumber
      if(!phone){
        wx.removeStorageSync('userinfo')
        wx.removeStorageSync('token')
        wx.showToast({
          title: '请重新登录',
          icon: 'none',
          duration: 2000
        })
        this.onShow()
      }
      that.setData({
        phoneMark : true,
        userPhone : phone
      })
      request({
        url: '/user/updateInfo', data: {
          phoneNum: that.data.userPhone
        }, method: 'PUT'
      })
        .then(result => {
          console.log(result);
        })
      wx.setStorageSync('userPhone', phone)
    })
  },


  // 跳转到我买到的页面
  jmp_buy(){
    wx.navigateTo({
      url: '/pages/buy/buy',
      success: (result) => {
          console.log('147')
      },
      fail: (err) => {console.log(err)},
      complete: () => {}
    }); 
  },

  // 跳转到我卖出的页面
  jmp_sell(){
    wx.navigateTo({
      url: '/pages/sell/sell',
      success: (result) => {
          console.log('147')
      },
      fail: (err) => {console.log(err)},
      complete: () => {}
    }); 
  },

  // 跳转到待付款的页面
  jmp_pay(){
    wx.navigateTo({
      url: '/pages/pay/pay',
      success: (result) => {
          console.log('258')
      },
      fail: (err) => {console.log(err)},
      complete: () => {}
    }); 
  },
  // 跳转到公众号
  jmp_gzh(){
    wx.navigateTo({
      url: `../../pages/advertisement/advertisement?url=https://mp.weixin.qq.com/s/Knniad3zWd4RVwpQ31v50A`
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    // 调接口拿收货地址的宿舍信息
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // console.log(store);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {   
    // 从本地缓存拿用户信息
    var value = wx.getStorageSync('userinfo')
    if (value) {
      this.setData({
        isStatus: true,
        users: value
      }),
        console.log(value)
    }
    else{
      this.setData({
        isStatus: false,
      })
    }
    // 从本地缓存拿用户地址
    var value_add = wx.getStorageSync('add')
    if (value_add) {
      this.setData({
        mark: true,
        address: value_add
      }),
        console.log(value_add)
    }

    // 从本地缓存拿用户号码
    var value_phone = wx.getStorageSync('userPhone')
    if (value_phone) {
      this.setData({
        phoneMark: true,
        userPhone: value_phone
      }),
        console.log(value_phone)
    }
    else{
      this.setData({
        phoneMark: false,
      })
    }
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})